package io.renren.modules.doc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.doc.dao.DocumentDao;
import io.renren.modules.doc.entity.DocumentEntity;
import io.renren.modules.doc.service.DocumentService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Map;

@Service("documentService")
public class DocumentServiceImpl extends ServiceImpl<DocumentDao, DocumentEntity> implements DocumentService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String title = (String)params.get("title");
        String categoryId = (String)params.get("categoryId");

        IPage<DocumentEntity> page = this.page(
            new Query<DocumentEntity>().getPage(params),
            new QueryWrapper<DocumentEntity>()
                .like(StringUtils.isNotBlank(title), "title", title)
                .eq(StringUtils.isNotBlank(categoryId), "category_id", categoryId)
                .eq("del_flag", 0)
                .orderByDesc("create_time")
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdate(DocumentEntity document) {
        if (document.getId() == null) {
            document.setStatus(0); // 新建为草稿状态
            document.setDelFlag(0);
        }
        this.saveOrUpdate(document);
        return false;
    }

    @Override
    public DocumentEntity getDocumentDetail(Long id) {
        return this.getOne(new QueryWrapper<DocumentEntity>()
            .eq("id", id)
            .eq("del_flag", 0));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDocument(Long[] ids) {
        // 逻辑删除
        Arrays.asList(ids).forEach(id -> {
            DocumentEntity document = new DocumentEntity();
            document.setId(id);
            document.setDelFlag(1);
            this.updateById(document);
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void publishDocument(Long id) {
        DocumentEntity document = new DocumentEntity();
        document.setId(id);
        document.setStatus(1); // 设置为已发布状态
        this.updateById(document);
    }
}
